import {
  reqCartList,
  reqAddSkuNum,
  reqDeleteCart,
  reqCheckCart
} from "@/api"

const state = {
  cartList: []
}
const mutations = {
  GETCARTLISY(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  async getCartList({commit}) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit("GETCARTLISY", result.data);
    }
  },
  async getAddSkuNum({commit}, {skuId,num}) {
    let result = await reqAddSkuNum(skuId, num)
    return result
  },
  async getDeleteCart({commit}, skuId) {
    let result = await reqDeleteCart(skuId)
    return result
  },
  //修改选中状态
  async getCheckCart({commit}, {skuId,isChecked}) {
    console.log(isChecked)
    let result = await reqCheckCart(skuId, isChecked)
    if (result.code == 200) {
      return 'ok';
    } else {
      return Promise.reject(new Error('失败'))
    }
  },
  //删除全部选中
  getDeleteAllCheckedCart({dispatch,getters}){
  
    let  pos  =  []
    getters.cartList.cartInfoList.forEach(item=>{
    let Pms  =   item.isChecked=="1"?dispatch("getDeleteCart",item.skuId):''
    pos.push(Pms)
    })
  return  Promise.all(pos)
  },
  getisAllChecked({dispatch,state},checked){
      let  pos  =  []
    state.cartList[0].cartInfoList.forEach(item=>{
    let Pms  =  dispatch("getCheckCart",{skuId:item.skuId,isChecked:checked})
    pos.push(Pms)
    })
      return  Promise.all(pos)

  }
  
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },
  // cartInfoList(state){
  //   return state.cartList[0].cartInfoList||[]
  // }

}


export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters

}
